//
//  STNetworkTools.swift
//  STVVeibo
//
//  Created by leergou on 16/7/22.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

import UIKit
import AFNetworking

// 网络请求枚举
enum RequestType: String{
    case GET = "GET"
    case POST = "POST"
}

class STNetworkTools: AFHTTPSessionManager {
    
    // 全局访问点
    static let shardTools: STNetworkTools = {
        
        let tools = STNetworkTools()
        // 指定反序列化器
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    // 发送请求
    func request(type: RequestType, urlString: String, parameters: AnyObject?, success:(response: AnyObject?)->(),failure:(error: NSError)->()) {
        
        if type == RequestType.GET {
            
            GET(urlString, parameters: parameters, progress: nil, success: { (_, res) in
                
                success(response: res)
                }, failure: { (_, err) in
                    failure(error: err)
            })
        } else {
            
            POST(urlString, parameters: parameters, progress: nil, success: { (_, res) in
                
                success(response: res)
                
                }, failure: { (_, err) in
                    failure(error: err)
            })
        }
    }
}


//MARK: 请求 oauth界面数据
extension STNetworkTools{
    
    func oauthLoadUserAccount(code: String, success:(response: AnyObject?)->(), failure:(error: NSError)->()){
        
        // 请求的urlString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":APPREDIRECT_URI
        ]
        
        // 发送请求
        request(RequestType.POST, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    
    // 请求用户信息
    func oauthLoadUserInfo(userAccount: STUserAccount, success:(response: AnyObject?)->(), failure:(error:NSError)->()) {
        
        // 获取用户信息
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = [
            "access_token":userAccount.access_token!,
            "uid":userAccount.uid!
        ]
        
        // 发送请求
        request(RequestType.GET, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}

//MAKR: - 获取首页信息
extension STNetworkTools{
    
    func homeLoadData(sinceId: Int64, maxId: Int64, success:(response: AnyObject?)->(), failure:(error: NSError)->()){
        
        /*
        https://api.weibo.com/2/statuses/home_timeline.json
        
        access_token
        
        */
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let parameters = ["access_token":STUserAccountViewModel.sharedUserAccountTools.accessToken!,
            "since_id":"\(sinceId)",
            "max_id":"\(maxId)"

        ]
        
        request(RequestType.GET, urlString: urlString, parameters: parameters, success: success, failure: failure)
    }
}

//MARK: 发布微博
extension STNetworkTools{
    
    // 发送文字微博
    func composeUpdate(status: String, success:(response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求的url
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        // 请求参数
        let parameters = [
            "access_token":STUserAccountViewModel.sharedUserAccountTools.accessToken!,
            "status":status
        ]
        // 发送请求
        request(RequestType.POST, urlString: urlString, parameters: parameters, success: success, failure: failure)
    }
    
    // 发送图片微博
   
    func composeUpload(status: String,imageList: [UIImage], success:(response: AnyObject?)->(), failure:(error: NSError)->()){
        
        /*
        https://upload.api.weibo.com/2/statuses/upload.json
        post
        
        
        */
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        let parameters = [
            "access_token":STUserAccountViewModel.sharedUserAccountTools.accessToken!,
            "status":status
        ]
        // 请求必须用POST方式提交，并且注意采用multipart/form-data编码方式；即表单形式
        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
            /*
            
            let data = UIImagePNGRepresentation(self.pictureView.imageList.first!)!
            
            STNetworkTools.shardTools.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
            
            formdata.appendPartWithFileData(data, name: "pic", fileName: "oooo", mimeType: "application/octet-stream")
    
            */
            
            // 发送多张图片
            // 遍历图片数组,拼接二进制 data
            for  index in 0..<imageList.count{
                
                let data = UIImagePNGRepresentation(imageList[index])!
                formdata.appendPartWithFileData(data, name: "pic", fileName: "oooo", mimeType: "application/octet-stream")
            }
            
            }, progress: nil, success: { (_, response) -> Void in
                
                success(response: response)
                
            }) { (_, error) -> Void in
                
                failure(error: error)
        }
    }

    
    
    
    
}









